package com.sgcc.nfc.lock.presentation.logs

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.OperationLog
import com.sgcc.nfc.lock.domain.usecase.GetLogsUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch

@HiltViewModel
class LogsViewModel @Inject constructor(
    private val getLogsUseCase: GetLogsUseCase
) : ViewModel() {

    private val _logs = MutableLiveData<List<OperationLog>>(emptyList())
    val logs: LiveData<List<OperationLog>> = _logs

    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _error = MutableLiveData<String?>()
    val error: LiveData<String?> = _error

    init {
        loadLogs()
    }

    fun loadLogs() {
        viewModelScope.launch {
            _isLoading.value = true
            _error.value = null
            
            when (val result = getLogsUseCase(page = 1, pageSize = 100)) {
                is NetworkResult.Success -> {
                    _logs.value = result.data.data
                }
                is NetworkResult.Error -> {
                    _error.value = result.message
                }
                is NetworkResult.Loading -> {
                    // Loading state already set
                }
            }
            
            _isLoading.value = false
        }
    }
}
